package validators;

import java.util.List;
import java.util.ResourceBundle;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import dtos.UserDTO;
import utils.UserDAORemote;


@FacesValidator("validators.UsernameDuplicateValidator")
public class UsernameDuplicateValidator implements Validator {
	@EJB
	UserDAORemote udr;

	ResourceBundle bundle = ResourceBundle.getBundle(
			"languageSettings.language", FacesContext.getCurrentInstance()
					.getViewRoot().getLocale());
	
	public UsernameDuplicateValidator(){
	}
	
	/**
	 * @param context UIComponent component, Verifies if the username is
	 *            already used or not
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String newUsername = (String) value;
		List<UserDTO> userList = udr.getAllUsersByUsername(newUsername);
		if (!userList.isEmpty()) {
			FacesMessage fMessage = new FacesMessage(
					bundle.getString("Validators_UsernameDuplicateValidator_Error"));
			throw new ValidatorException(fMessage);
		} 

	}
}
